import React, { useEffect, useState } from "react";
import { Table, Pagination, Badge, DatePicker } from "antd";
import queryString from "query-string";
import { quotaList } from "../../services/quotaApi";

import styles from "./historyRecord.less";

const { RangePicker } = DatePicker;

const defaultOrder = {
  columnKey: "createTime",
  order: "descend"
};

const dateFormat = "YYYY-MM-DD";

function HistoryRecord(props) {
  const { location } = props;
  const { msgSourceId } = queryString.parse(location.search);

  const [range, updateTime] = useState([]);

  const [filters, updateFilters] = useState({});
  const [sorters, updateSorters] = useState(defaultOrder);

  const [currentPage, updatePage] = useState(1);
  const [currentPageSize, updatePageSize] = useState(10);
  const [listData, updateListData] = useState([]);
  const [total, updateTotal] = useState(0);

  const [loading, updateLoading] = useState(false);

  const getValueFormFilters = propertyOfFilters => {
    if (filters) {
      const arr = filters[propertyOfFilters];
      if (arr && arr.length > 0) {
        return arr;
      }
      return [];
    }
    return [];
  };

  // 请求
  const fetchList = async () => {
    // 请求列表数据
    updateLoading(true);
    const [start, end] = range || [];
    const newparams = {
      // UUID: searchValue,
      msgSourceId,
      quotaType: getValueFormFilters("smsQuota.quotaType")[0],
      effectiveStatus: getValueFormFilters("smsQuota.effectiveStatus")[0],
      updateTimeOrderBy: { ascend: "asc", descend: "desc" }[
        sorters.columnKey === "createTime" && sorters.order
      ], // 正序-asc 倒序-desc
      updateTimeBegin: start ? start.format(dateFormat) : undefined,
      updateTimeEnd: end ? end.format(dateFormat) : undefined,
      pageNum: currentPage,
      pageSize: currentPageSize
    };
    const { errCode, datas, totalCount } = await quotaList(newparams);
    updateLoading(false);
    if (errCode === 0) {
      updateListData(datas);
      updateTotal(totalCount);
    } else {
      updateListData([]);
      updateTotal(0);
    }
  };

  // 监听状态变更，更新表格内容
  useEffect(() => {
    fetchList();
  }, [msgSourceId, filters, currentPage, currentPageSize, sorters, range]);

  const onPageChange = _page => {
    updatePage(_page);
  };

  const onPageSizeChange = (_cur, _size) => {
    updatePageSize(_size);
    updatePage(1);
  };

  const render = text => (text ? <span title={text}>{text}</span> : "-");
  const columns = [
    {
      title: "消息源名称",
      dataIndex: "msgSourceName",
      render
    },
    {
      title: "短信配额类型",
      dataIndex: "smsQuota.quotaType",
      // 1-年度 2-月度
      render: text => {
        let str = null;
        switch (text) {
          case 1: // 已发布
            str = "按年度";
            break;
          case 2: // 未发布
            str = "按月份";
            break;
          default:
            break;
        }
        return render(str);
      },
      filterMultiple: false,
      filters: [
        {
          text: "按年度",
          value: 1
        },
        {
          text: "按月份",
          value: 2
        }
      ],
      filteredValue: getValueFormFilters("smsQuota.quotaType")
    },
    {
      title: "短信配额",
      dataIndex: "quotaCount",
      render
    },
    {
      title: "生效状态",
      dataIndex: "smsQuota.effectiveStatus",
      render: text => {
        let config = {};
        switch (text) {
          case 1:
            config = { color: "green", text: "生效" };
            break;
          case 2:
            config = { color: "red", text: "未生效" };
            break;
          case 3:
            config = { status: "orange", text: "失效" };
            break;
          default:
            break;
        }
        return <Badge {...config} />;
      },
      filterMultiple: false,
      filters: [
        {
          text: "生效",
          value: 1
        },
        {
          text: "未生效",
          value: 2
        },
        {
          text: "失效",
          value: 3
        }
      ],
      filteredValue: getValueFormFilters("smsQuota.effectiveStatus")
    },
    {
      title: "有效起始时间",
      dataIndex: "smsQuota.effectiveBeginTime",
      render
    },
    {
      title: "有效截止时间",
      dataIndex: "smsQuota.effectiveEndTime",
      render: text => {
        if (text === "2199-01-01 00:00:00") {
          return "永久";
        }
        return render(text);
      }
    },
    {
      title: "配置时间",
      dataIndex: "createTime",
      sorter: true,
      sortOrder: sorters.order,
      render
    }
  ];

  return (
    <div className={styles.root}>
      <div
        style={{
          marginBottom: "8px",
          display: "flex",
          justifyContent: "flex-end"
        }}
      >
        <RangePicker
          value={range}
          placeholder={["配置开始时间", "配置结束时间"]}
          onChange={dates => {
            updateTime(dates);
            updatePage(1);
          }}
        />
      </div>
      <Table
        scroll={listData.length===0?{x:false}:{ x: 1000 }}
        size="middle"
        columns={columns}
        dataSource={listData}
        pagination={false}
        loading={loading}
        rowKey="smsQuotaId"
        onChange={(pagination, _filters, _sorter) => {
          updateSorters(_sorter);
          updateFilters(_filters);
          updatePage(1);
        }}
      />
      <div
        style={{
          display: "flex",
          justifyContent: "flex-end",
          marginTop: "8px",
          marginBottom: "10px"
        }}
      >
        <Pagination
          current={currentPage}
          pageSize={currentPageSize}
          onChange={onPageChange}
          onShowSizeChange={onPageSizeChange}
          total={total}
          showQuickJumper
          showSizeChanger
          showTotal={_total => `共有${_total}条`}
        />
      </div>
    </div>
  );
}

export default HistoryRecord;
